package tasks

import (
	"UpdateManagerServer/dbmgr"
	"UpdateManagerServer/models"
	"os"
	"path/filepath"
	"time"

	"github.com/beego/beego/v2/core/logs"
)

var GloabalTimer *time.Timer

var stopCh chan struct{}

func CleanExpiredTokens() error {
	logs.Info("begin clean version token")

	err := dbmgr.GlobalBaseRepo.ClearToken()
	return err
}

func ClearVersionFile() error {
	logs.Info("begin clean version file")

	lsFlor := models.ListDirectories("FileList")
	mapIDS, err := dbmgr.GlobalBaseRepo.CheckMissingIDs(lsFlor)
	if err != nil {
		logs.Error("ClearVersionFile, err: %s", err.Error())
		return err
	}

	for key, isDelete := range mapIDS {
		if isDelete {
			pathIndex := filepath.Join("FileList", key)
			if err := os.RemoveAll(pathIndex); err != nil {
				logs.Error("删除失败: %s (%v)\n", key, err)
			} else {
				logs.Info("成功删除: %s\n", key)
			}
		}
	}

	return nil
}

func TaskFunc() {
	CleanExpiredTokens()
	//ClearVersionFile()
}

func InitTimeTask() {
	stopCh = make(chan struct{})
	go startFixedInterval(1*time.Minute, TaskFunc)
}

func startFixedInterval(interval time.Duration, task func()) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop() // 必须释放资源

	for {
		select {
		case <-ticker.C:
			go task() // 异步执行（避免阻塞后续触发）
		case <-stopCh: // 外部控制退出
			return
		}
	}
}

func CloseTimer() {
	close(stopCh)
}
